"""
Copyright 2009 Texas A&M University
 
Licensed under the Apache License, Version 2.0 (the "License"); you may not use 
this file except in compliance with the License. You may obtain a copy of the 
License at

http://www.apache.org/licenses/LICENSE-2.0
  
Unless required by applicable law or agreed to in writing, software distributed 
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
CONDITIONS OF ANY KIND, either express or implied. See the License for the 
specific language governing permissions and limitations under the License. 
"""

import unittest
import httplib

from metalib import connection



class MockHttpResponse(object):
    def __init__(self, body, status=200, reason='OK', headers={}, msg=''):
        self._body = body
        self.status = status
        self.reason = reason
        self.headers = headers
        self.msg = msg
        self.version = 11
    
    def read(self, amt=None):
        return self._body
    
    def getheader(self, name, default=None):
        return self.headers.get(name,default)
    
    def getheaders(self):
        return self.headers

class MockHttpConnection(object):
    open = False
    responses = []
    requests = []
    
    def connect(self):
        self.open = True
    
    def close(self):
        self.open = False
    
    def request(self, method, url, body=None, headers=None):
        self.requests.append(method,url,body,headers)
    
    def getresponse(self):
        if len(self.responses) > 0:
            return self.responses.pop()
        
        if len(self.requests) > 0:
            return self.requests.pop()
        
        return None

class ConvertValueToElementTest(unittest.TestCase):
    def test_string(self):
        """ Test conversion of a string value """
        value = connection.convertValueToElement('tag','value')
        self.assertEqual(value.tag,'tag')
        self.assertEqual(value.text,'value')
        self.assertEqual(value.attrib, {})
    
    def test_dict(self):
        """ Test conversion of a dictionary value """
        value = connection.convertValueToElement('tag',{'subtag':'subvalue1'})
        self.assertEqual(value.tag,'tag')
        self.assertEqual(len(value.getchildren()),1)
        self.assertEqual(value.getchildren()[0].tag,'subtag')
        self.assertEqual(value.getchildren()[0].text,'subvalue1')
    
    def test_invalid(self):
        """ Test conversion of an invalid value """
        self.assertRaises(ValueError,connection.convertValueToElement,'tag',[])

class ConvertDictToElementTest(unittest.TestCase):
    def test_single_value(self):
        """ Test conversion of a single entry dictionary with a string value """
        values = connection.convertDictToElement({'tag':'value'})
        self.assertEqual(len(values),1)
        self.assertEqual(values[0].tag,'tag')
        self.assertEqual(values[0].text,'value')
    
    def test_multiple_values(self):
        """ Test conversion of a single entry dictionary with a list value """
        values = connection.convertDictToElement({'tag':['value1','value2']})
        self.assertEqual(len(values),2)
        for v in values:
            self.assertEqual(v.tag,'tag')
            self.assert_(v.text in ['value1','value2'])
    
    def test_invalue_value(self):
        """ Test conversion of a single entry dictionary with an invalid value """
        self.assertRaises(TypeError,connection.convertDictToElement,{'tag':5})
        
class MetalibConnectionTest(unittest.TestCase):
    def setUp(self):
        self.conn = connection.MetalibConnection('localhost','1234','Y',timeout=5)
        self.httpconn = MockHttpConnection()
        self.conn._getConnection = lambda s: self.httpconn 

    def test_post(self):
        pass
    
    def test_handle_resposne(self):
        pass
    
    def test_connect(self):
        pass
    

def test_suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.TestLoader().loadTestsFromTestCase(ConvertValueToElementTest))
    suite.addTest(unittest.TestLoader().loadTestsFromTestCase(ConvertDictToElementTest))
    suite.addTest(unittest.TestLoader().loadTestsFromTestCase(MetalibConnectionTest))
    return suite

if __name__ == '__main__':
    unittest.TextTestRunner(verbosity=2).run(test_suite())